# -*- coding: utf-8 -*-
# __author__ = "sword"

if True:
    # from os import path
    # print('__file__=', path.abspath(__file__))
    # parentPath = path.abspath(path.dirname(__file__))
    # print('parentPath=', parentPath)
    # toolPath = path.dirname(path.join(parentPath, 'tool/init.py'))
    # print('toolPath=', toolPath)
    # import sys
    # sys.path.append(toolPath)
    # from init import *
    from tool.init import *


class Welfare():
    def __init__(self):
        self.round = 0
        self.sleep_time = 3

        pass

    '''
    关闭广告
    '''

    def close_ad(self):
        for i in range(60):
            sleep(1.0)
            tag = poco("android:id/content"). \
                child("android.widget.RelativeLayout"). \
                child("android.widget.RelativeLayout"). \
                child("android.widget.TextView")
            if tag.exists():
                text = tag.attr('text')
                # print(text)
                print('...')
                if text is not None:
                    if text.count('已观看') > 0:
                        # print('已观看')
                        print('have watched')
                        break
            link = poco("video-content")
            if link.exists():
                # print('链接出现')
                print('there is a link')
                break
        touch((102, 86))
        sleep(1.0)

    '''
    抽奖
    '''

    def circulate_0(self):
        print('[+] start to find double')
        from PIL import Image
        img_name = "hello.jpg"
        x1, x2, x3, x4 = 247, 475, 706, 939
        y1, y2 = 792, 1061
        poss = [
            (x1, y1),
            (x2, y1),
            (x3, y1),
            (x4, y1),
            (x1, y2),
            (x2, y2),
            (x3, y2),
            # (x4, y2),
        ]
        g_check = 128

        for _, pos in enumerate(poss):
            print('[-] _=', _)
            snapshot(img_name)
            im = Image.open(img_name)
            print('[-] im.size=', im.size)
            print('[-] im.getpixel(pos)', im.getpixel(pos))
            r, g, b = im.split()
            g_value = g.getpixel(pos)

            if g_check == g_value:
                # print('[+] 去翻倍', child)
                print('[-] go to double', pos)
                touch(pos)
                self.close_ad()
        # print('[+] 无须翻倍')
        print('[+] no double')
        sleep(3)

        # print('[+] 立即抽奖')
        print('[+] go to gamble')
        touch((906, 1487))
        sleep(1)
        

        # print('[-] 抽两次开始')
        print('[-] twice gamble, start')
        for i in range(2):
            poco.click([0.5, 0.5677083333333334])
        # print('[-] 抽两次结束')
        print('[-] twice gamble, end')

        # print('[-] 抽三次开始')
        print('[-] triple gamble, start')
        for i in range(2):
            # print('[-] 看视频...')
            print('[-] watch ad...')
            poco.click([0.5, 0.5677083333333334])
            self.close_ad()
            sleep(2.0)

            # print('[-] 抽奖...')
            print('[-] gamble...')
            poco.click([0.5, 0.5677083333333334])
        # print('[+] 抽三次结束')
        print('[+]  triple gamble, end')
        touch((527, 1753))

        biggift = poco(text="本周每天看视频，周日领大礼包")
        biggift2 = poco(text='看视频再领起点币，最高10点')
        # print('[+] 周日领大礼包开始')
        print('[+] sunday big gift, start')

        # touch((557, 1289))
        while True:
            if biggift.exists():
                # print('[-] "本周每天看视频，周日领大礼包"')
                print('[-] "this week"')
                biggift.click()
                self.close_ad()
                sleep(2.0)
                biggift = poco(text="本周每天看视频，周日领大礼包")
                biggift2 = poco(text='看视频再领起点币，最高10点')
            elif biggift2.exists():
                # print('[-] "看视频再领起点币，最高10点"')
                print('[-] "ten coins"')
                biggift2.click()
                self.close_ad()
                sleep(2.0)
                biggift = poco(text="本周每天看视频，周日领大礼包")
                biggift2 = poco(text='看视频再领起点币，最高10点')
            else:
                break
        # print('[+] 无周日领大礼包')
        print('[+] sunday big gift, end')
        pass

    '''
    章节末尾红包
    '''

    def run_1_hongbao(self):
        tv_hongbao_value = poco("com.qidian.QDReader:id/tv_hongbao_value")
        if tv_hongbao_value.exists() == False:
            # print('[-] 彩蛋章')
            print('[-] picture chapter')
        else:
            tv_hongbao_value_text = tv_hongbao_value.attr('text')
            # print('[-] 红包数量 = {}'.format(tv_hongbao_value_text))
            print('[-] hongbao_value = {}'.format(tv_hongbao_value_text))
            if tv_hongbao_value_text != '0个':
                print('[-] tap hongbao')
                hongbao = poco("com.qidian.QDReader:id/tx_hongbao")
                hongbao.click()

                print('[-] check hongbao')
                if poco('com.qidian.QDReader:id/hongbaoInfoTv').attr('text') != '发送1个月票红包':
                    print('[-] yes hongbao')
                    poco("com.qidian.QDReader:id/button_text_id").click()
                    self.close_ad()
                    return

        print('[-] no hongbao')
        pass

    '''
    章节末尾看视频
    '''

    def run_1_end_gift(self):
        end_gift = poco("com.qidian.QDReader:id/button_text_id")
        if end_gift.exists() == False:
            # print('[-] 没有')
            print('[-] no gift')
        else:
            # print('[-] 看视频')
            print('[-] watch ad')
            end_gift.click()
            self.close_ad()
            return
        pass
    '''
    抽红包 or 章节末尾看视频
    '''

    def circulate_1(self, isHongbao):
        while True:
            self.round += 1
            print('[+] ---------round: {}'.format(self.round))

            if self.round > 15:
                print('[!] goobye.')
                break

            if poco("com.qidian.QDReader:id/mTitleTextView").exists():
                # raise Exception('完结')
                raise Exception('book end')

            print('[-] call the bar')
            y_coordination = 0.45
            poco.click([0.5, y_coordination])

            print('[-] check coment')
            while True:
                sleep(1.0)
                y_coordination += 0.05
                if poco("com.qidian.QDReader:id/comment_count_text").exists() or poco("com.qidian.QDReader:id/comment_count").exists():
                    print('[-] try, tap y_coordination = {}'.format(y_coordination))
                    poco("com.qidian.QDReader:id/fake_top").click()
                else:
                    print('[-] ok, tap y_coordination = {}'.format(y_coordination))
                    break
                poco.click([0.5, y_coordination])

            print('[-] tap next_chapter')
            next_chapter = poco("com.qidian.QDReader:id/tvNextPage")
            if next_chapter.exists() is False:
                raise Exception('[!] no next_chapter')
            next_chapter.click()
            print('[-] exit the bar')
            poco.click([0.5, 0.5])
            keyevent("KEYCODE_VOLUME_UP")
            sleep(1.0)

            caidan_flag = False
            if poco(text='打赏').exists() is False:
                # print('[-] 彩蛋章节')
                print('[-] picture chapter')
                keyevent("KEYCODE_VOLUME_UP")
                caidan_flag = True

            if isHongbao is True:
                self.run_1_hongbao()
            else:
                self.run_1_end_gift()

            if caidan_flag:
                keyevent("KEYCODE_VOLUME_DOWN")
                keyevent("KEYCODE_VOLUME_DOWN")
            else:
                keyevent("KEYCODE_VOLUME_DOWN")
            sleep(1.0)
            pass
        pass

    '''
    中间和结尾的浮动奖励
    '''

    def circulate_2(self):
        while True:
            self.round += 1
            print('[+] ---------round: {}'.format(self.round))

            amid_gift = poco("com.qidian.QDReader:id/tvTitle")
            end_gift = poco("com.qidian.QDReader:id/button_text_id")
            # caidan = poco("com.qidian.QDReader:id/username")
            if amid_gift.exists():
                # print('[-] 发现 amid_gift')
                print('[-] there is a amid_gift')
                amid_gift.click()
                self.close_ad()
            elif end_gift.exists():
                # print('[-] 发现 end_gift')
                print('[-] there is a end_gift')
                end_gift.click()
                self.close_ad()
            else:
                # print('[-] 没有')
                print('[-] no gift')
                pass
            keyevent("KEYCODE_VOLUME_DOWN")
            pass
        pass

    pass


def main():
    welfare = Welfare()
    if str(target) == '0':
        welfare.circulate_0()
    # 红包
    elif str(target) == '1':
        welfare.circulate_1(isHongbao=True)
    # 章节末尾看视频
    elif str(target) == '2':
        welfare.circulate_1(isHongbao=False)
    elif str(target) == '3':
        welfare.circulate_2()
    else:
        print('no select')


if __name__ == '__main__':
    main()
